'use strict';

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const { contentId, type, pinned, adminId } = event;

  if (!contentId || !type || typeof pinned !== 'boolean') {
    return {
      code: 400,
      msg: '缺少必要参数',
      data: null
    };
  }

  try {
    const contentCollection = db.collection('add-content');
    
    // 更新置顶状态
    const updateData = {
      pinned: pinned,
      update_time: new Date()
    };

    if (pinned) {
      updateData.pinned_time = new Date();
      updateData.pinned_admin = adminId || 'admin';
    } else {
      updateData.pinned_time = null;
      updateData.pinned_admin = null;
    }

    const result = await contentCollection.doc(contentId).update(updateData);

    // 记录操作日志
    const auditLogCollection = db.collection('audit_logs');
    await auditLogCollection.add({
      target_type: type,
      target_id: contentId,
      action: pinned ? 'pinned' : 'unpinned',
      admin_id: adminId || 'admin',
      create_time: new Date()
    });

    return {
      code: 200,
      msg: pinned ? '置顶成功' : '取消置顶成功',
      data: {
        contentId: contentId,
        pinned: pinned,
        updated: result.updated
      }
    };
  } catch (error) {
    console.error('置顶操作失败:', error);
    return {
      code: 500,
      msg: '置顶操作失败',
      data: null
    };
  }
};
